package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomException;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.mapper.CategoryMapper;
import com.itheima.service.ICategoryService;
import com.itheima.service.IDishService;
import com.itheima.service.ISetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * category业务实现类
 *
 * @author hua
 * @since 2022/11/2 12:17
 */
@Service
public class CategoryServiceImpl extends ServiceImpl <CategoryMapper, Category> implements ICategoryService{
    /**
     * 菜品
     */
    @Autowired
    private IDishService dishService;
    /**
     * 套餐
     */
    @Autowired
private ISetmealService setmealService;

    /**
     * 根据Id删除分类
     * @param categoryId
     */
    @Override
    public void deleteById(Long categoryId) {
     //根据分类的类型,来采取不同的查询
        //要查询的内容,有菜品和套餐
        // 根据传入id,查询数据库,看一下这个id是否真的在数据库中有数据
        Category category = this.getById(categoryId);
        if (category==null){
            throw new CustomException("传递的参数不正确");
        }
        //根据分类的类型,来采取不同的查询
        switch (category.getType()){
            //1.菜品分类
            case 1:
                //查询菜品
                LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
                // 分类id,根据分类id查询菜品
                dishQueryWrapper.eq(Dish::getCategoryId,categoryId);
                // 只查询符合这个条件的数据的数量就可以
                int dishCount = this.dishService.count(dishQueryWrapper);
                // 如果查询的数量大于0
                if (dishCount >0){
                    throw new CustomException("该分类下还存在菜品,不允许删除");
                }
                break;
            case 2:
                //查询套餐
                LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
                // 分类id,根据分类id查询菜品
                setmealQueryWrapper.eq(Setmeal::getCategoryId,categoryId);
                // 只查询符合这个条件的数据的数量就可以
                int count = this.setmealService.count();
                //如果查询的数量大于0
                if (count >0){
                    throw new CustomException("该分类下还存在菜品,不允许删除");
                }
                break;
            default:
                throw new CustomException("传入的类型不正确");
        }
        // 删除操作
        this.removeById(categoryId);
    }
}
